// pages/binds/binds.js
const app = getApp();
var old_value = [-1,-1,-1,-1];
var waiting = false;
Page({

  data: {
    bgTextStyle: 'dark',
    scrollTop: '200rpx',
    bgColor: '#ff0000',
    bgColorTop: '#00ff00',
    bgColorBottom: '#0000ff',
    nbTitle: '住宅绑定',
    nbLoading: false,
    nbFrontColor: '#000000',
    nbBackgroundColor: '#ffffff',
    pageStyle: "color:#333333;background-color: #f1f1f1;",
    userInfo: {
      nickName: "",
      addr: "address",
      avatar: ""
    },
    xiaoqu: [],
    unit: [],
    house: [],
    room: [],
    values:[0,0,0,0],
    old_value:[-1,-1,-1,-1],
    owner: {username:'',xiaoqu:'',room_code:'',heat_code:''},
    binds: [],
    listMode: true,
    bindMode: true,
    phoneNumber: '',
    phoneCode: '',
    showOwn: false,
    useCode: false,
    showCode: false,
    ready: false
  },
  onLoad: function (options) {
    let v = this;
    v.getMyBinds();
  },
  onReady: function () {
  },
  onShow: function () {
    let v = this;
    // v.getMyBinds();
  },
  getMyBinds: function() {
    let v = this;
    v.setData({listMode: true, bindMode: true, showOwn: false});
    let url = app.globalData.host + '/api/user/owner_list';
    wx.request({
      url: url, data: {token: app.globalData.token},
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          let l = r.data.list || [];
          console.log("getMyBinds",l);
          v.setData({binds: l});
        }
      }
    })
  },
  switchUse(ev){
    let v = this;
    let ds = ev.target.dataset;
    let useCode = ds.tf == 1 ? true: false; //!v.data.useCode;
    // console.log("switchUse",useCode,ds, ev);
    v.setData({useCode:useCode,bindMode: true, phoneCode: '',phoneNumber:''});
  },
  doAdd(path) {
    let v = this;
    v.setData({listMode: false,bindMode:true,values:[0,0,0,0],old_value:[-1,-1,-1,-1],xiaoqu:[],unit:[],house:[],room:[]});
    v.getAddrInfo();
    console.log("doAdd",path);
  },
  getAddrInfo(type = 0){
    let v = this;
    v.setData({hasChange: false});
    let url = app.globalData.host + '/api/search/owner_options';
    wx.request({
      url: url, data: {type: type || 0, token: app.globalData.token},
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          let l = r.data.options || [];
          for(let k in l) {
            l[k].selected = (k == 0);
          }
          v.setData({listMode: false,xiaoqu:l});
          console.log("getAddrInfo",l);
          v.bindChange({detail: { value:[0,0,0,0]} },0);
        }
      }
    })
  },
  bindChange(ev,changeId = 0){
    let v = this;
    let clear = (ev.type == 'change');
    let dt = ev.detail.value || [];
    const keys = ['xiaoqu',"house","unit","room"];
    console.log("bindChange ev",changeId,"clear:",clear,dt,ev, v.data.old_value);
    let diff = 0;
    let old = v.data.old_value;
    let changeKey = keys[0];
    let data = {type: changeId + 1 || 0};
    let needUp = false;
    if(clear) {
      for(let i = 0, il = 4; i < il; i++) {
        if(old[i] != dt[i] && (i < 3)) needUp = true;
      }
      if(!needUp) {
        console.log("needUp false");
        // return;
      } else {
        old = [-1,-1,-1,-1];
        v.setData({old_value: old});
      }
    }
    for(let k in old) {
      let ik = parseInt(k);
      let oldv = old[ik];
      let newv = dt[k];
      let ikey = keys[ik];
      if(oldv != newv) {
        changeId = ik;
        changeKey = keys[changeId];
        old[ik] = dt[ik]; 
        
        console.log("changeId:",ik,changeKey," ",oldv,"=>",newv, old);
        if(clear) {
          let reset = {room:[]};
          if(ik > 1)  reset.unit = [];
          if(ik > 0)  reset.house = [];
          if (needUp) v.setData(reset);
        }
        if(v.data[ikey][dt[k]]) data[ikey] = v.data[ikey][dt[k]].value;
        break;
      } else {
        
        console.log("old data:",ikey,dt[k],);
        if(v.data[ikey][dt[k]]) data[ikey] = v.data[ikey][dt[k]].value;
      }
    }
    data.type = changeId + 1;
    
    let url = app.globalData.host + '/api/search/owner_options';
    // console.log("changeId",changeId,"key",changeKey,v.data);
    let val = 0;
    let idx = dt[changeId];
    if(v.data[changeKey][idx])val = v.data[changeKey][idx].value;
    data[changeKey] = val;
    console.log('request wait',waiting,data);
    if(waiting) return;
    waiting = true;
    wx.request({
      url: url, data: data,
      success (res) {
        waiting = false;
        let r = res.data;
        if(r.code == 200 && r.data) {
          let l = r.data.options || [];
          for(let k in l) {
            l[k].selected = (k == 0);
          }
          let sdata = {old_value: old};
          let nextId = changeId+1;
          let setKey = keys[nextId];
          if(setKey) sdata[setKey] = l;
          if(data.type == 4) {
            sdata.owner = r.data.owner || {};
          }
          v.setData(sdata);
          console.log("bindChange set ",data.type,nextId,setKey,sdata,old);
          if(data.type < 4) {
            // console.log("bindChange set after"); 
            v.bindChange({detail: { value:dt} });
          }
        }
      },
      complete(){
        waiting = false;
      }
    })
  },
  doBindPhone(ev){
    let v = this;
    console.log("doBindPhone");
    v.setData({bindMode: true});
  },
  doBindCard(){
    let v = this;
    console.log("doBindCard");
    let url = app.globalData.host + '/api/user/bind_owner';
    let phone = v.data.phoneNumber;
    let code  = v.data.phoneCode;
    let owner_id = v.data.owner.owner_id;
    wx.request({
      url: url, data: {phone:phone,code:code,owner_id:owner_id,token: app.globalData.token},
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          wx.showToast({ title: r.msg || '绑定成功',icon:'none'})
          
          v.getMyBinds();
        } else {
          wx.showToast({ title: r.msg || '绑定失败',icon:'none'})
        }
      }
    })
  },
  doGetCode(ev) {
    let v = this;
    console.log("doGetCode");
    let url = app.globalData.host + '/api/ajax/get_phone_code';
    let phone = v.data.phoneNumber;
    let owner_id = v.data.owner.owner_id;
    wx.request({
      url: url, data: {phone:phone,owner_id:owner_id,token: app.globalData.token},
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          wx.showToast({ title: r.msg || '已发送验证码',icon:'none',duration: 5000});
          // v.getMyBinds();
        } else {
          wx.showToast({ title: r.msg || '请求错误',icon:'none'});
        }
      }
    })
  },
  doUnBindCard(ev){
    let v = this;
    console.log("doUnBindCard", ev);
    let ds = ev.target.dataset;
    let url = app.globalData.host + '/api/user/unbind_owner';
    let phone = v.data.phoneNumber;
    wx.showModal({
      title: '移动绑定',
      content: '确定要移除吗?',
      success (res) {
        if (res.confirm) {
          console.log('用户点击确定');
          wx.request({
            url: url, data: {owner_id:ds.uid,token: app.globalData.token},
            success (res) {
              let r = res.data;
              if(r.code == 200 && r.data) {
                wx.showToast({ title: r.msg || '成功',icon:'none'})
              } else {
                wx.showToast({ title: r.msg || '请求错误',icon:'none'})
              };
              v.getMyBinds();
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
    
  },
  doSetDefault(ev){
    let v = this;
    console.log("doSetDefault", ev);
    let ds = ev.target.dataset;
    let owner_id = ds.uid;
    if(!owner_id) return;
    console.log("doSetDefault", owner_id);
    // wx.navigateTo({ url: "/pages/orderPay/pay?owner_id=" + owner_id});
    let url = app.globalData.host + '/api/user/bind_default_owner';
    wx.request({
      url: url, data: {owner_id:owner_id, token: app.globalData.token},
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          wx.showToast({ title: r.msg || '成功',icon:'none'})
        } else {
          wx.showToast({ title: r.msg || '请求错误',icon:'none'})
        };
        v.getMyBinds();
      }
    });
  },
  doNavToPay(ev){
    let v = this;
    console.log("doNavToPay", ev);
    let ds = ev.target.dataset;
    let owner_id = ds.uid;
    if(!owner_id) return;
    wx.navigateTo({ url: "/pages/orderPay/pay?owner_id=" + owner_id});
  },
  bindInputCode(ev) {
    let v = this;
    let newVal  = ev.detail.value;
    let heat_code = v.data.owner.heat_code;
    let showCode = false;
    if(newVal && newVal.toLocaleUpperCase) {
      let up = newVal.toLocaleUpperCase();
      console.log('bindInputCode', up,heat_code);
      showCode = (up == heat_code);
    }
    if(newVal) {
      v.setData({phoneCode: newVal,showCode: showCode});
    }
    
  },
  bindInput(ev) {
    let v = this;
    let newVal  = ev.detail.value;
    if(newVal) {
      v.setData({phoneNumber: newVal});
    }
    console.log('bindInput', newVal,ev);
  },
  onHide: function () {
  },
  onUnload: function () {
  },
  onPullDownRefresh: function () {
  },
  onReachBottom: function () {
  },
  onShareAppMessage: function () {
  }
})